package com.example.hsh.homefragment.rx.presenter;

import android.content.Context;

import com.example.hsh.homefragment.base.BaseApplication;
import com.example.hsh.homefragment.rx.RxManager;
import com.example.hsh.homefragment.rx.view.RxBaseView;

import java.lang.ref.SoftReference;

/**
 * Created by HSH on 2016/12/26.
 */

public abstract class RxBasePresenter<T extends RxBaseView> {
    protected SoftReference<T> attachUi ;
    protected RxManager rxManager;

    public void attach(T ui) {
        if (ui != null) {
            attachUi = new SoftReference<T>(ui);
        }
        if (rxManager == null) {
            rxManager = new RxManager();
        }
    }

    public void detach() {
        if (attachUi != null) {
            attachUi.clear();
        }
        if (rxManager != null) {
            rxManager.clear();
        }
    }

    protected Context getContext() {
        Context context = null;
        T ui = getObserverUi();
        if (ui != null) {
            context = ui.getPresenterContext();
        }
        if (context == null) {
            context = BaseApplication.getApplication().getApplicationContext();
        }
        return context;
    }

    protected T getObserverUi() {
        return attachUi == null ? null : attachUi.get();
    }

    protected boolean isUiAttached() {
        return attachUi != null && attachUi.get() != null;
    }

    //拿到RxBaseView的子View
    @SuppressWarnings (value="unchecked")
    protected <AU extends T> AU getActualUi() {
        if (!isUiAttached()) {
            return null;
        }

        RxBaseView ui = getObserverUi();
        AU au;
        try {
            au = (AU) ui;
        } catch (Exception e) {
            au = null;
        }
        return au;
    }
}
